const Service = require('egg').Service;
const COS = require('cos-nodejs-sdk-v5');
const fs = require('fs');
const os = require('os');
const path = require('path');

class FileService extends Service {
  streamToBuffer(stream) {
    return new Promise((resolve, reject) => {
      const buffers = [];
      stream.on('error', reject);
      stream.on('data', data => buffers.push(data));
      stream.on('end', () => resolve(Buffer.concat(buffers)));
    });
  }

  async upload(file) {
    const filename = file.filename;
    const randomName = Date.now() + '_' + Math.round(Math.random() * 100);
    const postfix_filename = filename.substring(filename.lastIndexOf('.'), filename.length);
    const uploadPath = this.app.config.upload_path;
    const filePath = uploadPath + randomName + postfix_filename;

    // 获取文件大小
    const buffer = await this.streamToBuffer(file);
    const cos = new COS({
      SecretId: this.app.config.qcloud.secretId,
      SecretKey: this.app.config.qcloud.secretKey,
    });


    const data = await (new Promise((resolve, reject) => {
      cos.putObject({
        Bucket: this.app.config.qcloud.bucket,
        Region: this.app.config.qcloud.region,
        Key: filePath,
        // Key: file.name,
        TaskReady(tid) {
          const TaskId = tid;
        },
        onProgress(progressData) {

        },
        Body: buffer,
      }, function(err, data) {
        if (!err) {
          resolve(data);
        } else {
          reject(err.Message);
        }
      });
    }));

    return this.app.config.qcloud.origin + filePath;
  }
}

module.exports = FileService;
